package com.boarsoft.boar.flow;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import com.boarsoft.flow.core.bean.TransactionHandler;

public class SimpleTxHandler implements TransactionHandler<TransactionStatus>, TransactionDefinition {
	protected PlatformTransactionManager transactionManager;

	/** */
	protected String name;
	/** */
	protected int propagation = 0;
	/** */
	protected int isolation = -1;
	/** */
	protected int timeout = -1;
	/** */
	protected boolean readOnly = false;
	/** */
	protected TransactionDefinition definition;

	@Override
	public TransactionStatus begin(Object data) {
		name = Thread.currentThread().getName();
		return transactionManager.getTransaction(definition == null ? this : definition);
	}

	@Override
	public void commit(TransactionStatus tx) {
		if (tx.isCompleted()) {
			return;
		}
		transactionManager.commit(tx);
	}

	@Override
	public void rollback(TransactionStatus tx) {
		if (tx.isCompleted()) {
			return;
		}
		transactionManager.rollback(tx);
	}

	public PlatformTransactionManager getTransactionManager() {
		return transactionManager;
	}

	public void setTransactionManager(PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	// ------------
	
	@Override
	public int getPropagationBehavior() {
		return propagation;
	}

	@Override
	public int getIsolationLevel() {
		return isolation;
	}

	@Override
	public String getName() {
		return name;
	}
	
	//-------------

	public int getPropagation() {
		return propagation;
	}

	public void setPropagation(int propagation) {
		this.propagation = propagation;
	}

	public int getIsolation() {
		return isolation;
	}

	public void setIsolation(int isolation) {
		this.isolation = isolation;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public boolean isReadOnly() {
		return readOnly;
	}

	public void setReadOnly(boolean readOnly) {
		this.readOnly = readOnly;
	}
}
